package cn.mdmm.user.service.impl.user;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;

import cn.mdmm.user.common.MessageConstant;
import cn.mdmm.user.entity.response.ResponseBodyToOne;
import cn.mdmm.user.entity.user.UserCodeInfoModel;
import cn.mdmm.user.entity.user.request.UserCodeInfoRequest;
import cn.mdmm.user.mapper.user.UserCodeInfoMapper;
import cn.mdmm.user.service.user.UserCodeInfoService;
import cn.modoumama.common.exception.RequiredException;
import cn.modoumama.common.exception.ServiceException;
import cn.modoumama.common.utils.ConfigProperty;
import cn.modoumama.common.utils.SmsUtil;
import cn.modoumama.common.utils.StringUtils;
import cn.modoumama.service.base.impl.BaseServiceImpl;


/**
* 类名称：UserCodeInfo对象定义<br>
* 类描述：业务实现类<br>
* 类生产方式：工具自动生成代码<br>
* 创建人：邓强<br>
* 创建时间：2017-06-01 17:22:30<br>
* 修改人：  <br>
* 修改时间：<br>
* 修改备注：<br>
* @version   V1.0
*/

@Service(version = "1.0")
public class UserCodeInfoServiceImpl extends BaseServiceImpl<UserCodeInfoModel,Integer> implements UserCodeInfoService{
	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	public void setMapper(UserCodeInfoMapper genericMapper) {
		super.setGenericMapper(genericMapper);
	}
	
	@Autowired
	UserCodeInfoMapper userCodeInfoMapper;

	//------------------请在此添加自定义方法（开始）------------------
	@Override
	public ResponseBodyToOne sendCode(UserCodeInfoRequest request) {
		ResponseBodyToOne response = new ResponseBodyToOne();
		
		if(StringUtils.isBlank(request.getPhone())){
			throw new RequiredException("phone");
		}else{
			boolean flag = true;
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("phone", request.getPhone());
			paramMap.put("isUse", 0);
			paramMap.put("time", 1);
			Integer count = countByCondition(paramMap);
			if(count>=1){
				flag = false;
				throw new ServiceException(MessageConstant.SMS_MINUTE_OVER);
			}else{
				paramMap.put("time",60);
				count = countByCondition(paramMap);
				if(count>=5){
					flag = false;
					throw new ServiceException(MessageConstant.SMS_60MINUTE_OVER);
				}else{
					paramMap.put("time",1440);
					count = countByCondition(paramMap);
					if(count>=10){
						flag = false;
						throw new ServiceException(MessageConstant.SMS_DAY_OVER);
					}
				}
			}
			
			if(flag){
				//生成验证码
				String code = String.valueOf(Math.round(Math.random() * 8999 + 1000));
				
				//发送验证码
				try {
					JSONObject smsParam = new JSONObject();
					smsParam.put("code", code);
					// 发送短信
					SendSmsResponse sendSmsResponse = SmsUtil.sendByAliyun(request.getPhone(), ConfigProperty.getProperty("sms.aliyun.template"), smsParam.toJSONString(), ConfigProperty.getProperty("sms.aliyun.sign"));
					if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
						UserCodeInfoModel userCodeInfoModel = new UserCodeInfoModel();
						userCodeInfoModel.setRequestId(sendSmsResponse.getRequestId());
						userCodeInfoModel.setBizId(sendSmsResponse.getBizId());
						userCodeInfoModel.setPhone(request.getPhone());
						userCodeInfoModel.setCode(code);
						userCodeInfoModel.setIsUse(0);
						userCodeInfoModel.setNumber(0);
						userCodeInfoModel.setCreateTime(new Date());
						insert(userCodeInfoModel);
						response.setData(code);
						logger.info("手机号码‘"+request.getPhone()+"’的验证码是："+code+"---------发送成功");
					}
				} catch (Exception e) {
					logger.error(e.getMessage());
					throw new ServiceException(MessageConstant.SYSTEM_ERROR);
				}
			}
			
			if(!flag){
				throw new ServiceException(MessageConstant.SMS_SEND_FAIL);
			}
		}
		return response;
	}
	
	public ResponseBodyToOne login() {
		ResponseBodyToOne responseBody = new ResponseBodyToOne();
		
		return responseBody;
	}

	@Override
	public void verificationCode(String phone, String code) {
		UserCodeInfoModel userCodeInfoModel = userCodeInfoMapper.getLastCodeInfo(phone);
		if(userCodeInfoModel == null){
			throw new ServiceException(MessageConstant.SMS_INVALID);
		}else if(userCodeInfoModel.getIsUse()==1){
			throw new ServiceException(MessageConstant.SMS_VALIDATION_CODE_ALREADY_USE);
		}else if(userCodeInfoModel.getNumber()>=5){
			throw new ServiceException(MessageConstant.SMS_MAX_ERROR_OVER);
		}else if(!userCodeInfoModel.getCode().equals(code)){
			userCodeInfoModel.addNumber();
			updateById(userCodeInfoModel);
			throw new ServiceException(MessageConstant.VERIFICATION_CODE_ERROR);
		}else{
			userCodeInfoModel.setIsUse(1);
			updateById(userCodeInfoModel);
		}
	}
	//------------------请在此添加自定义方法（结束）------------------
}
